<template>
  <div
      class="list-container"
      :class="containerClasses"
      @scroll="handleScroll"
  >
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <div class="loading-text">{{ loadingText }}</div>
    </div>

    <!-- 空状态 -->
    <div v-if="showEmpty" class="empty-state">{{ emptyText }}</div>

    <!-- 列表内容 -->
    <ul
        class="list"
        :class="listClasses"
        :style="listStyles"
        role="list"
    >
      <li
          v-for="(item, index) in visibleItems"
          :key="getItemKey(item, index)"
          class="list-item"
          :class="getItemClasses(item, index)"
          @click="handleItemClick(item, $event)"
          @dblclick="handleItemDoubleClick(item)"
      >
        <!-- 默认插槽 -->
        <slot v-if="$slots.default" :item="item" :index="index" />
        <template v-else>
          {{ getItemDisplay(item) }}
        </template>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { computed, ref, watch, onMounted, onUnmounted } from 'vue'

const props = defineProps({
  items: {
    type: Array,
    default: () => []
  },
  itemKey: {
    type: String,
    default: 'id'
  },
  emptyText: {
    type: String,
    default: 'No data available'
  },
  size: {
    type: String,
    default: 'medium',
    validator: (value) => ['small', 'medium', 'large'].includes(value)
  },
  bordered: {
    type: Boolean,
    default: false
  },
  striped: {
    type: Boolean,
    default: false
  },
  loading: {
    type: Boolean,
    default: false
  },
  loadingText: {
    type: String,
    default: 'Loading...'
  },
  direction: {
    type: String,
    default: 'vertical',
    validator: (value) => ['vertical', 'horizontal'].includes(value)
  },
  justifyContent: {
    type: String,
    default: 'flex-start'
  },
  alignItems: {
    type: String,
    default: 'stretch'
  },
  selectedItems: {
    type: Array,
    default: () => []
  },
  multiple: {
    type: Boolean,
    default: false
  },
  selectable: {
    type: Boolean,
    default: false
  },
  // 新增搜索和排序相关props
  searchQuery: {
    type: String,
    default: ''
  },
  sortBy: {
    type: [String, Function],
    default: ''
  }
})

const emit = defineEmits([
  'update:selectedItems',
  'itemClick',
  'itemDoubleClick',
  'loadMore'
])

// 计算属性
const showEmpty = computed(() => !props.loading && props.items.length === 0)
const containerClasses = computed(() => [
  `size-${props.size}`,
  { bordered: props.bordered }
])
const listClasses = computed(() => [
  `direction-${props.direction}`,
  { striped: props.striped }
])
const listStyles = computed(() => ({
  justifyContent: props.justifyContent,
  alignItems: props.alignItems
}))

// 处理虚拟列表（简化版）
const visibleItems = computed(() => {
  // TODO: 实现完整虚拟列表逻辑
  return props.items
})

// 处理搜索和排序
const processedItems = computed(() => {
  let result = [...props.items]

  // 搜索过滤
  if (props.searchQuery) {
    const query = props.searchQuery.toLowerCase()
    result = result.filter(item => {
      if (typeof item === 'object') {
        return Object.values(item).some(value =>
            String(value).toLowerCase().includes(query))
      }
      return String(item).toLowerCase().includes(query)
    })
  }

  // 排序
  if (props.sortBy) {
    if (typeof props.sortBy === 'function') {
      result.sort(props.sortBy)
    } else if (typeof props.sortBy === 'string') {
      result.sort((a, b) => {
        const valA = typeof a === 'object' ? a[props.sortBy] : a
        const valB = typeof b === 'object' ? b[props.sortBy] : b
        return valA > valB ? 1 : -1
      })
    }
  }

  return result
})

// 方法
const getItemKey = (item, index) => {
  return typeof item === 'object' ? item[props.itemKey] : index
}

const getItemDisplay = (item) => {
  return typeof item === 'object' ? item[props.itemKey] : item
}

const getItemClasses = (item, index) => {
  const isSelected = props.selectedItems.some(selected =>
      selected === (typeof item === 'object' ? item[props.itemKey] : item)
  )
  return [
    `item-size-${props.size}`,
    {
      selected: isSelected,
      striped: props.striped && index % 2 === 0
    }
  ]
}

// 事件处理
const handleItemClick = (item, event) => {
  if (props.selectable) {
    let newSelected = [...props.selectedItems]
    const itemValue = typeof item === 'object' ? item[props.itemKey] : item

    if (props.multiple) {
      const index = newSelected.indexOf(itemValue)
      index === -1 ? newSelected.push(itemValue) : newSelected.splice(index, 1)
    } else {
      newSelected = newSelected[0] === itemValue ? [] : [itemValue]
    }

    emit('update:selectedItems', newSelected)
  }

  emit('itemClick', item, event)
}

const handleItemDoubleClick = (item) => {
  emit('itemDoubleClick', item)
}

// 滚动加载
const handleScroll = (e) => {
  const { scrollTop, scrollHeight, clientHeight } = e.target
  const threshold = 100
  if (scrollHeight - scrollTop - clientHeight < threshold) {
    emit('loadMore')
  }
}

// 键盘导航
const handleKeyDown = (e) => {
  // TODO: 实现键盘导航逻辑
}

onMounted(() => {
  window.addEventListener('keydown', handleKeyDown)
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown)
})
</script>

<style scoped>
.list-container {
  position: relative;
  overflow-y: auto;
}

.list {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
}

.list.direction-vertical {
  flex-direction: column;
}

.list.direction-horizontal {
  flex-direction: row;
  flex-wrap: wrap;
}

.list-item {
  padding: 8px 12px;
  cursor: pointer;
  transition: all 0.2s;
}

.list-item.selected {
  background-color: #e3f2fd;
}

.list-item:hover:not(.selected) {
  background-color: #f5f5f5;
}

.size-small .list-item {
  padding: 4px 8px;
  font-size: 12px;
}

.size-medium .list-item {
  padding: 8px 12px;
  font-size: 14px;
}

.size-large .list-item {
  padding: 12px 16px;
  font-size: 16px;
}

.bordered {
  border: 1px solid #ddd;
  border-radius: 4px;
}

.striped .list-item:nth-child(even) {
  background-color: #f8f8f8;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  border: 3px solid #f3f3f3;
  border-radius: 50%;
  border-top: 3px solid #3498db;
  width: 30px;
  height: 30px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-state {
  padding: 20px;
  text-align: center;
  color: #666;
}
</style>